###
	Outline

	- Global Vars
	- Core Code (run once)
		-- add empty table
		-- subscription
			-- couch view - get data
				-- parse data
				-- save parsed data into new data
			-- loop sorted new data and create table rows
			-- hide rows depending on organization or individual
			-- event handling on generated links
###

define [
	'jquery'
	'template'
	'lib/jquery.couch.js'
	'helper'
], ($, undef, undef, H) ->
	S = {}
	$.fn.mb_search_result = (SamCtx) ->

	# --- Global Variables and Function ---------------

		ins = @
		$this = $(@)
		S = SamCtx
		type = ""
		$tpl = $('<tr>').html '
				<td class="col_id"><%= index %></td>
				<td class="col_name"><%= name %></td>
				<td class="col_org"><%= org_name %></td>
				<td class="col_addr"><%= address %></td>
				<td class="col_phone"><%= phone %></td>'

	# --- Core code of plugin -------------------------

		unless @mb_plugin()
			@mb_plugin 'search_result'

			# Initialization
			$(@).hide()

			# Main subscription
			# _key is the query to be entered as key to couchdb view
			# _orgview is either "org" or "ind"
			$.subscribe "mb.query", (e, {search_term: _key, search_type: _orgview}) =>
				if (type = _orgview) is "org" then _org = "_org"  else _org = ""
				return if _key.length is 0

				# Show the plugin (search results) on first publish, or first search
				if $(@).is(":hidden") then $(@).show()

				# Get Couch view and return all the queried results
				$.couch.db("vcn-members").view "app/search#{_org}", 
					key: _key
					error: (err) ->
						console.log err
						return false
					success: (data) -> 
						resultlist = []

						# Remove all the table rows except the header (cleans out the table)
						$('tr:not(:has(th))', ins).remove()

						for i of data.rows
							# sh stands for short-hand to make this var shorter
							# objFormat is a custom helper function to format those all caps entries
							# to conform to a normal casing.
							sh = H.objFormat(data.rows[i].value)

							# Name column: Create concatenation for name in format LAST, FIRST
							_name = "#{sh.last_name}, #{sh.first_name}"

							# Phone column: only show one phone number at a time in priority
							# of the array below
							_phone = ""
							for phone in ["tel_home", "tel_contact", "tel_work", "tel_fax"]
								continue if not sh[phone]? or sh[phone] is ""
								_phone = "#{phone.replace("tel_", "").toCaps().charAt(0)}: #{sh[phone]}"
								break

							# Address column: Create concatenation string of the full address
							_addr = "#{sh.street_address} #{sh.city}, #{sh.province}, #{sh.postal_code}"

							resultlist[i] =
								_id 		: sh._id
								name 	: _name
								phone 	: _phone
								address 	: _addr
								org_name 	: sh.org_name

							# Search anything undefined in the object or values with the text "undefined" and replace
							# with "" string
							a[m] = (a[m] or= "")?.replace(/undefined/g, '') for m of a = resultlist[i]
							resultlist[i] = a

						# Iterate through the newly defined object with the parsed properties and append them to table on the 
						# current page
						for j of resultlist.sort(H.sortby('name'))
							i = resultlist[j]
							i.index = Number(j) + 1

							# Create the table rows
							content = S.content $tpl, i
							$('tbody', ins).append $('<tr>')
									.attr("id": i._id, "index": Number(j) + 1)
									.append content

						# Hide and show Organization column depending on view type
						if _orgview  is 'org' then $('th:contains("Organization"), .col_org').show()
						else $('th:contains("Organization"), .col_org', ins).hide()

						$('tr:visible:eq(1)', ins).trigger('mousedown')


		# --- Event Handlers ---------------------------------------------

			# Mousedown event handling on table rows (highlighting)
			$('.results', ins).on "mousedown", 'tr:not(:has(th))', ->
				$('.results', ins).addClass('focus') if $('.selected', ins).length isnt 0
				$('.selected', ins).removeClass('selected')

				# Apply classname "selected" to the current clicked table row
				$(@).addClass('selected')

			# Event handling for clicking on View Donor button
			$('[name="view_donor"]', ins).click () -> viewDonor()

			# Custom viewDonor function
			viewDonor = () ->
				$.publish "mb.donor", {donor_id : $this.find('.selected').attr('id')}
				S.app.setLocation "#/donor_detail"

			# Create a "loss of focus" on the table when search box is focused by removing classname "focus"
			# from the table
			$('[name="search_term"]').focus () -> $('.results', ins).removeClass('focus')

			$(document).on 'keydown', (e) ->
				return if $('#search').is(":hidden")
				# If the table of results has focus class (or is focused), then make sure it is
				# by removing focus from the search box
				if $('.results', ins).hasClass('focus') then $('[name="search_term"]', @).blur()

				# Pressing tab focuses on the table and defocuses the search field
				if e.keyCode is 9
					$('.results', ins).addClass('focus')
					$('[name="search_term"]', @).blur()
					return false
				# If the table is not in focus, then ignore this event handler
				return if not $('.results', ins).hasClass('focus')

				switch e.keyCode
					# Keypress Down
					when 40
						# Find the next available table row and trigger a mousedown
						$('.selected', ins).nextAll("tr:visible:eq(0)").trigger('mousedown')
						return false
					# Keypress Up
					when 38
						# Find the previous available table row and trigger a mousedown
						$('.selected', ins).prevAll('tr:visible:eq(0)').trigger('mousedown')
						return false
					# Keypress Enter
					when 13
						viewDonor()
						return false
					else
						return true

		return @
	return
